﻿// 
// Project: Soapi.JS
// http://soapijs.codeplex.com
// http://stackapps.com/questions/494
// 
// Copyright 2010, Sky Sanders
// Dual licensed under the MIT or GPL Version 2 licenses.
// http://soapi.info/code/js/license.aspx
// 
// Date: July 2 2010 
// Version: RC2.1 - API Version 0.9 Revision 2010.06.29.001
// 
using System;
using System.IO;
using System.Web;

namespace Salient.Web
{
    /// <summary>
    ///   Monitors requests for compressed scripts (and css soon) and serves
    ///   them up with the proper headers
    /// </summary>
    public class GZipScriptModule : IHttpModule
    {
        #region IHttpModule Members

        /// <summary>
        ///   TODO: implement as async
        ///   TODO: implement last modified
        ///   TODO: send paths to monitor to configuration element
        /// </summary>
        /// <param name = "context"></param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginRequest;
        }

        public void Dispose()
        {
        }

        #endregion

        private void BeginRequest(object sender, EventArgs e)
        {
            HttpApplication context = (HttpApplication) sender;

            string filePath = context.Request.FilePath;

            // are we monitoring this and is it gzipped and is it a js file
            if (!filePath.StartsWith("/build/scripts")
                || Path.GetExtension(filePath).ToUpper() != ".GZ"
                || Path.GetExtension(Path.GetFileNameWithoutExtension(filePath)).ToUpper() != ".JS")
            {
                return;
            }

            // check to see if the user accepts gzip

            foreach (String acceptType in context.Request.AcceptTypes)
            {
                switch (acceptType.ToUpper())
                {
                    case "*/*":
                    case "GZIP":
                        context.Response.ContentType = "application/javascript";
                        context.Response.AddHeader("content-encoding", "gzip");
                        context.Response.WriteFile(context.Request.PhysicalPath);
                        context.Response.End();
                        break;
                    default:
                        break;
                }
            }
        }
    }
}